using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.GameAOT;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_LevelMapQuestPanel : UIBaseNode
    {
        #region Template Generate,don't modify

        protected class UIB_UIN_LevelMapQuestPanel
        {
            #region ObjectBinding Generate

            public ExText questTitle { protected set; get; }
            public ExText questDesc { protected set; get; }
            public ExLoopVerticalScrollRect rewards { protected set; get; }
            public ExButton btnStopTrace { protected set; get; }
            public ExButton btnGoto { protected set; get; }
            public ExText questTarget { protected set; get; }
            public ExButton btnTrace { protected set; get; }

            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<ExText>("questTitle", out var __tbv0);
                questTitle = __tbv0;
                __binding.TryGetVariableValue<ExText>("questDesc", out var __tbv1);
                questDesc = __tbv1;
                __binding.TryGetVariableValue<ExLoopVerticalScrollRect>("rewards", out var __tbv2);
                rewards = __tbv2;
                __binding.TryGetVariableValue<ExButton>("btnStopTrace", out var __tbv3);
                btnStopTrace = __tbv3;
                __binding.TryGetVariableValue<ExButton>("btnGoto", out var __tbv4);
                btnGoto = __tbv4;
                __binding.TryGetVariableValue<ExText>("questTarget", out var __tbv5);
                questTarget = __tbv5;
                __binding.TryGetVariableValue<ExButton>("btnTrace", out var __tbv6);
                btnTrace = __tbv6;
            }

            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify


        #region fields

        private LoopScrollAdapter<UIN_MapQuestRewardItem> _rewardList;

        private IReadOnlyList<int> _rewards;

        private int _questCid;

        private int _questProviderEntityId;
        #endregion fields

        #region properties

        protected UIB_UIN_LevelMapQuestPanel ui { get; set; }
        protected UIMsgDispatcher uiMsgDispatcher => _msgDispatcher as UIMsgDispatcher;

        #endregion properties

        protected override void BeforeInit()
        {
            ui = new UIB_UIN_LevelMapQuestPanel();
            ui.InitBinding(csObjBind);
        }

        protected override void OnInit()
        {
            ui.btnStopTrace.AddClickEvent(OnBtnStopTraceClick);
            ui.btnGoto.AddClickEvent(OnBtnGotoClick);
            ui.btnTrace.AddClickEvent(OnBtnTraceClick);
            _rewardList = InitLoopScroll<UIN_MapQuestRewardItem>(ui.rewards, RefreshRewardItem);
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }

        public void Refresh(int questCid, int questProviderEntityId)
        {
            _questCid = questCid;
            _questProviderEntityId = questProviderEntityId;
            if (questProviderEntityId == 0)
            {
                ui.btnStopTrace.SetActive(questCid == GameDataCenter.PlayerData.quest.trackQuestCid);
                ui.btnTrace.SetActive(!ui.btnStopTrace.gameObject.activeSelf);
                ui.btnGoto.SetActive(true);
            }
            else
            {
                var tracingEntity = GameplayAreaManager.Instance.curSceneArea?.GetTrackingEntity();
                var tracingEntityId = tracingEntity.id;
                ui.btnStopTrace.SetActive(questProviderEntityId == tracingEntityId);
                ui.btnTrace.SetActive(questProviderEntityId != tracingEntityId);
                ui.btnGoto.SetActive(false);
            }

            var config = TableCenter.quest.Get(questCid);
            ui.questTitle.text = config.Name;
            ui.questTarget.text = config.TargetDescription;
            ui.questDesc.text = config.Description;
            _rewards = config.Reward;
            _rewardList.RefillCells(_rewards.Count / 2);
        }

        protected override void OnDispose()
        {
        }

        #region methonds

        private void OnBtnGotoClick()
        {
            var config = TableCenter.quest.Get(_questCid);
            var targetRegionCid = config.TargetRegion;
            var mapRoot = UIMapManager.Instance.GetMap(targetRegionCid);
            var entity = GameplayAreaManager.Instance.curSceneArea.GetEntityByMcid(config.TargetShowEntity.FirstOrDefault());
            var pos = entity?.transform?.position ?? Vector3.zero;
            var checkPoint = mapRoot.GetNearestCheckPointMcid(pos);
            if (checkPoint == null)
            {
                return;
            }

            if (GameplayAreaManager.Instance.curArea is not IGameplaySceneArea curArea)
            {
                return;
            }
            if (!FunctionModule.CheckIsOpenAndTip(FunctionType.MapTransmit))
                return;
            if (targetRegionCid == curArea.curRegionCid)
            {
                NoticeModule.ShowNotice(APIUIConst.NoticeCid_Teleport,
                    () =>
                    {
                        CLevelLogicModule.NetCore.CS_TeleportToEntity(checkPoint.entityId);
                        Close();
                    });
            }
            else
            {
                NoticeModule.ShowNotice(APIUIConst.NoticeCid_DifferentRegionTrace,
                    () => curArea.TeleportToRegion(targetRegionCid, checkPoint.entityId).Forget());
            }
        }

        private void OnBtnStopTraceClick()
        {
            if (_questProviderEntityId == 0)
            {
                DoStopTraceQuest().Forget();
            }
            else
            {
                if (belongWindow is not UILevelMap uiLevelMap) return;
                uiLevelMap.CancelTraceEntity().Forget();
                ui.btnStopTrace.SetActive(false);
                ui.btnTrace.SetActive(true);
            }

        }

        private void RefreshRewardItem(UIN_MapQuestRewardItem item, int index)
        {
            var cidIndex = 2 * index;
            var numIndex = 2 * index + 1;
            var itemCid = _rewards[cidIndex];
            var itemNum = _rewards[numIndex];
            var cfgItem = TableCenter.item.Get(itemCid);
            item.Show();
            item.Refresh(cfgItem, itemNum);
        }

        private async UniTaskVoid DoStopTraceQuest()
        {
            var result = await QuestModule.NetCore.CS_setTrackQuest(0);
            if (result.IsSuccess)
            {
                if (belongWindow is UILevelMap uiLevelMap)
                {
                    uiLevelMap.PopPanel();
                    UIMapManager.Instance.SetSelection(null);
                }
            }
        }

        private void OnBtnTraceClick()
        {
            if (_questProviderEntityId == 0)
            {
                DoTraceQuest().Forget();
            }
            else
            {
                if (belongWindow is not UILevelMap uiLevelMap) return;
                uiLevelMap.DoTraceEntity(_questProviderEntityId).Forget();
            }
        }

        private async UniTaskVoid DoTraceQuest()
        {
            var result = await QuestModule.NetCore.CS_setTrackQuest(_questCid);
            if (result.IsSuccess)
            {
                ui.btnTrace.SetActive(false);
                ui.btnStopTrace.SetActive(true);
            }
        }

        #endregion methonds
    }
}
